<template>
  <div class="curr-page">
    <div class="pt-5 d-flex jc-end ai-center">
      <el-button type="primary" @click="onSubmit" size="small"
        >立即创建</el-button
      >
      <el-button size="small">取消</el-button>
    </div>

    <!-- 车辆信息表单 -->
    <div class="pt-4">
      <el-form
        label-width="120px"
        ref="form"
        :model="FormData"
        :rules="rules"
        :inline="false"
      >
        <!-- tabs -->
        <el-tabs v-model="activeTabName" @tab-click="handleClick">
          <!-- base info -->
          <el-tab-pane label="基础信息" name="first">
            <el-form-item label="名称">
              <el-input v-model="FormData.name" style="width:300px"></el-input>
            </el-form-item>

            <el-form-item label="归属店铺">
              <el-select v-model="FormData.shopId">
                <el-option
                  v-for="(s_item, s_index) in shops"
                  :key="'shops' + s_index"
                  :label="s_item.name"
                  :value="s_item._id"
                >
                </el-option>
              </el-select>

              <span class="el-icon-circle-plus ml-3 mr-1"></span>
              <span @click="showCreateShopDialog = true">新建店铺</span>
            </el-form-item>

            <el-form-item label="图片">
              <el-upload
                class="avatar-uploader "
                :action="uploadUrl"
                :headers="getAuthHeaders"
                :show-file-list="false"
                :on-success="handleCarAvatarSuccess"
                :before-upload="beforeAvatarUpload"
              >
                <img
                  v-if="FormData.icon"
                  :src="FormData.icon"
                  style="height:60px;"
                  class="avatar"
                />
                <i v-else class="el-icon-plus avatar-uploader-icon"></i>
              </el-upload>
            </el-form-item>

            <el-form-item label="车龄">
              <el-input v-model="FormData.age" style="width:300px"></el-input>
            </el-form-item>

            <el-form-item label="里程">
              <el-input
                v-model="FormData.milage"
                style="width:300px"
              ></el-input>
            </el-form-item>

            <el-form-item label="价格">
              <el-input v-model="FormData.price" style="width:300px"></el-input>
            </el-form-item>
            <el-form-item label="变速器类型" style="width:300px">
              <el-input v-model="FormData.TransmissionType"></el-input>
            </el-form-item>
            <el-form-item label="品牌">
              <el-select v-model="FormData.brand">
                <el-option
                  v-for="(b_item, b_index) in brands"
                  :key="'brands' + b_index"
                  :label="b_item.name"
                  :value="b_item._id"
                >
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="车型">
              <el-select v-model="FormData.carModel">
                <el-option
                  v-for="(ca_item, ca_index) in carModel"
                  :key="'carModel' + ca_index"
                  :label="ca_item.name"
                  :value="ca_item._id"
                >
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="颜色">
              <el-select v-model="FormData.color">
                <el-option
                  v-for="(co_item, co_index) in color"
                  :key="'brands' + co_index"
                  :label="co_item.name"
                  :value="co_item._id"
                >
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="燃油类型">
              <el-select v-model="FormData.fuelType">
                <el-option
                  v-for="(f_item, f_index) in fuelType"
                  :key="'brands' + f_index"
                  :label="f_item.name"
                  :value="f_item._id"
                >
                </el-option>
              </el-select>
            </el-form-item>
          </el-tab-pane>

          <!-- pictures -->
          <el-tab-pane label="车辆详图" name="second">
            <!-- add btn -->
            <el-button
              size="small"
              class="my-3"
              v-if="!showPictureForm"
              @click="showPictureForm = true"
            >
              添加图片
            </el-button>
            <el-button v-else type="success" size="small" @click="addNewPicture"
              >确认添加</el-button
            >

            <!-- new picture form -->
            <div v-show="showPictureForm" style="width:600px">
              <!-- title -->
              <el-form-item label="名称">
                <el-input v-model="pictureForm.name">></el-input>
              </el-form-item>

              <!-- picture / icon url -->
              <el-form-item label="图片">
                <el-upload
                  class="avatar-uploader "
                  :action="uploadUrl"
                  :headers="getAuthHeaders"
                  :show-file-list="false"
                  :on-success="handleAvatarSuccess"
                  :before-upload="beforeAvatarUpload"
                >
                  <img
                    v-if="pictureForm.icon"
                    :src="pictureForm.icon"
                    style="height:60px;"
                    class="avatar"
                  />
                  <i v-else class="el-icon-plus avatar-uploader-icon"></i>
                </el-upload>
              </el-form-item>

              <!-- desc -->
              <el-form-item label="描述">
                <el-input
                  type="textarea"
                  v-model="pictureForm.description"
                ></el-input>
              </el-form-item>
            </div>

            <!-- 列表 -->
            <el-table :data="FormData.detailPics" border stripe>
              <el-table-column prop="name" label="标题"> </el-table-column>
              <el-table-column prop="description" label="描述">
              </el-table-column>
              <el-table-column label="图片">
                <template #default="scope">
                  <img :src="scope.row.icon" alt="" style="width:120px" />
                </template>
              </el-table-column>
              <el-table-column label="操作">
                <template #default="scope">
                  <el-link @click.prevent="deleteRow(scope.$index)">
                    删除</el-link
                  >
                </template>
              </el-table-column>
            </el-table>
          </el-tab-pane>
        </el-tabs>
      </el-form>
    </div>

    <!-- 创建店铺 -->
    <el-dialog v-model="showCreateShopDialog" width="60%">
      <template #title>
        <div class=" text-align">创建新的店铺</div>
      </template>

      <!-- 表单 -->
      <el-form
        :model="newShop"
        ref="shopForm"
        :rules="shopRules"
        label-width="80px"
        :inline="false"
        size="normal"
      >
        <el-form-item label="店铺名称">
          <el-input v-model="newShop.name"></el-input>
        </el-form-item>
        <el-form-item label="店铺地址">
          <el-input v-model="newShop.address"></el-input>
        </el-form-item>
        <el-form-item label="店龄">
          <el-input v-model="newShop.age"></el-input>
        </el-form-item>
        <el-form-item label="店铺图片">
          <el-input v-model="newShop.avatar"></el-input>
        </el-form-item>
      </el-form>

      <template #footer>
        <div class="dialog-footer">
          <el-button @click="submitNewShop" size="mini" type="primary">
            创建提交
          </el-button>
          <el-button @click="showCreateShopDialog = false" size="mini">
            关闭
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    return {
      FormData: {
        brand: "",
        age: null,
        milage: null,
        price: null,
        TransmissionType: null,
        detailPics: [],
      },

      showPictureForm: false,
      pictureForm: {
        name: null,
        description: null,
        icon: null,
      },

      // 表单验证
      rules: [],

      // 下拉列表内容
      brands: [],
      color: [],
      fuelType: [],
      carModel: [],

      // 店铺信息
      shops: [],
      showCreateShopDialog: false,
      newShop: {},
      shopRules: [],

      // tabs
      activeTabName: "first",
    };
  },

  computed: {
    uploadUrl() {
      return "http://localhost:3001/web/api/upload";
    },

    getAuthHeaders() {
      return {
        Authorization: `Bearer ${sessionStorage.token || ""}`,
      };
    },
  },

  methods: {
    fetchInitData() {
      this.fetchBrands();
      this.fetchCarModel();
      this.fetchColor();
      this.fetchFuelType();
      this.fetchShops();
    },

    // 切换 tab 钩子
    handleClick(tab, event) {
      console.log(tab, event);
    },

    // 新增 车辆图片
    addNewPicture() {
      this.FormData.detailPics.push(this.pictureForm);
      this.pictureForm = {};
      this.showPictureForm = false;
    },

    /**
     * 图片上传钩子
     */
    // 文件上传后验证
    handleAvatarSuccess(res, file) {
      console.log(res);
      console.log(file);
      this.pictureForm.icon = res.url;
    },

    handleCarAvatarSuccess(res, file) {
      console.log(res);
      console.log(file);
      this.FormData.icon = res.url;
    },

    // 文件上传前验证
    beforeAvatarUpload(file) {
      console.group("beforeAvatarUpload");
      console.log(file);
      // const isJPG = file.type === "image/jpeg";
      // const isLt2M = file.size / 1024 / 1024 < 2;
      // if (!isJPG) {
      //   this.$message.error("上传头像图片只能是 JPG 格式!");
      // }
      // if (!isLt2M) {
      //   this.$message.error("上传头像图片大小不能超过 2MB!");
      // }
      // return isJPG && isLt2M;
    },

    // 删除
    deleteRow(index) {
      this.FormData.detailPics.splice(index, 1);
    },

    //上传车辆
    async onSubmit() {
      this.FormData.userId = sessionStorage.userId;
      const res = await this.$http.post("car/create", this.FormData);
      this.$message({
        type: "success",
        message: "保存成功",
      });
      console.log(res);
    },

    // 新建店铺
    async submitNewShop() {
      this.newShop.userId = sessionStorage.userId;
      await this.$http.post("shop", this.newShop).then(() => {
        this.$message({
          type: "success",
          message: "创建成功",
        });
      });
      this.showCreateShopDialog = false;
      this.newShop = {};
    },

    async fetchBrands() {
      const res = await this.$http.get(`category/brand`);
      this.brands = res.data;
    },

    async fetchCarModel() {
      const res = await this.$http.get(`category/carModel`);
      this.carModel = res.data;
    },

    async fetchColor() {
      const res = await this.$http.get(`category/color`);
      this.color = res.data;
    },

    async fetchFuelType() {
      const res = await this.$http.get(`category/fuelType`);
      this.fuelType = res.data;
    },

    async fetchShops() {
      const res = await this.$http.get(`shop/user/${sessionStorage.userId}`);
      this.shops = res.data;
    },
  },

  created() {
    this.fetchInitData();
  },
};
</script>

<style lang="scss" scoped>
.curr-page {
  margin: 0 5rem 5rem 5rem;
}
</style>
